 //
//  SetNightModelViewController.m
//  ebook
//
//  Created by ChenNan on 16/3/23.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "SetNightModelViewController.h"
#import "SettimeModel.h"

@interface SetNightModelViewController ()<UITableViewDataSource, UITableViewDelegate, UIPickerViewDataSource, UIPickerViewDelegate>
@property (nonatomic, retain) UITableView *tableView;
@property (nonatomic, retain) UISwitch *swit;
@property (nonatomic, retain) UILabel *timeFromlabel;//time start
@property (nonatomic, retain) UILabel *timeTolabel;  //time end

@property (nonatomic, retain) UIPickerView *pickerView;
@property (nonatomic, retain) NSMutableArray *hoursArray;
@property (nonatomic, retain) NSMutableArray *minsArray;
@property (nonatomic, assign) BOOL isFirst;//YES表示：从－cell  NO表示：到－cell

@end

@implementation SetNightModelViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor clearColor];
    self.title = @"定时启动夜间模式";
    [self createBackBtn];
    
    UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, MTScreenW, MTScreenH) style:UITableViewStyleGrouped];
    tableView.delegate = self;
    tableView.dataSource = self;
    [self.view addSubview:tableView];
    _tableView = tableView;
    _swit = [[UISwitch alloc] init];
    _isFirst = YES;

    if (_isSwitchOn) {
        _swit.on = YES;
        [tableView addSubview:self.pickerView];
    }

    if (_timeStr) {
        NSArray *array = [_timeStr componentsSeparatedByString:@"-"];
        _timeFromlabel.text = array[0];
        _timeTolabel.text = array[1];
    } else {
        _timeStr = @"19:00-05:00";
    }
    
    //pickerView dataSource
    _hoursArray = [[NSMutableArray alloc] init];
    _minsArray = [[NSMutableArray alloc] init];
    [self setDataSources];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - set datasources
- (void)setDataSources
{
    for (int i = 0; i < 24; i ++) {
        NSString *str;
        if (i < 10) {
            str = [NSString stringWithFormat:@"0%d", i];
        } else {
            str = [NSString stringWithFormat:@"%d", i];
        }
        [_hoursArray addObject:str];
    }
    for (int i = 0; i < 60; i += 5) {
        NSString *str;
        if (i <10) {
            str = [NSString stringWithFormat:@"0%d", i];
        } else {
            str = [NSString stringWithFormat:@"%d", i];
        }
        [_minsArray addObject:str];
    }
}

#pragma mark - navi back btn
- (void)createBackBtn
{
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"back_arrow"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    backItem.tintColor = MTConfigColor(@"MTNavigationBar_leftItem_Color");
    self.navigationItem.leftBarButtonItem = backItem;
}

- (void)back
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewWillDisappear:(BOOL)animated {
    
    [super viewWillDisappear:animated];
    
    NSString *isOn = nil;
    isOn = [NSString stringWithFormat:@"%d", _swit.isOn];
    if (_sendTimeToSuper) {
        NSDictionary *dic = kPeriodTimeOfNight;
        if (!dic) {//userDefaults 没有数据
            _sendTimeToSuper(@"19:00", @"05:00", isOn);
        }  else {
            if (!_timeFromlabel || !_timeTolabel) {//临时变量为空
                _sendTimeToSuper(dic[@"fromTime"], dic[@"toTime"], isOn);
            } else {//从临时变量取值
                _sendTimeToSuper(_timeFromlabel.text, _timeTolabel.text, isOn);
            }
        }
    }
    
    [SettimeModel isInNightTimeInteval];
}

#pragma mark - table
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    if (_swit.on) {
        return 2;
    }
    return 1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 20;
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 20;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (_swit.on) {
        if (0 == section) {
            return 1;
        } else {
            return 2;
        }
    } else {
        return 1;
    }
    return 0;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
    if (_swit.on) {
        if (1 == section) {
            return @"设定开启夜间模式的时间段";
        }
    }
    return nil;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *inditifier = @"setNight";
    UITableViewCell *cell = [_tableView dequeueReusableCellWithIdentifier:inditifier];
    if (nil == cell) {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:inditifier];
    }
    //默认选中第一行
    [self chooseDefaultRow];

    if (0 == indexPath.section && 0 == indexPath.row) {
        cell.textLabel.text = @"允许定时开启夜间模式";
         _swit.frame = CGRectMake(MTScreenW-20-50, (cell.height-31)/2, 0, 0);
        [_swit addTarget:self action:@selector(siwitchChange) forControlEvents:UIControlEventValueChanged];
        [cell addSubview:_swit];
    }
    
    //separate timeStr for example:12:12-12:23
    NSArray *array = [_timeStr componentsSeparatedByString:@"-"];
        if (_swit.isOn) {
            if (1 == indexPath.section && 0 == indexPath.row) {
                cell.textLabel.text = @"从";
                cell.detailTextLabel.text = array[0];
                _timeFromlabel = cell.detailTextLabel;
            }
            if (1 == indexPath.section && 1 == indexPath.row) {
                cell.textLabel.text = @"到";
                cell.detailTextLabel.text = array[1];
                _timeTolabel = cell.detailTextLabel;
            }
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        [tableView deselectRowAtIndexPath:indexPath animated:YES];
    }
    if (1 == indexPath.section && 0 == indexPath.row) {
        [self clickfirstCell:YES timeStr:_timeFromlabel.text];
    }
    if (1 == indexPath.section && 1 == indexPath.row) {
        [self clickfirstCell:NO timeStr:_timeTolabel.text];
    }
}

#pragma mark 设置默认选中开始时间第几行
- (void)chooseDefaultRow
{
    NSIndexPath *selectedIndexPath = [NSIndexPath indexPathForRow:0 inSection:1];
    [_tableView selectRowAtIndexPath:selectedIndexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    //pickerView 自动滚到设置的时间点
    NSInteger row1 = 0, row2 = 0;
    NSArray *array = [[_timeStr componentsSeparatedByString:@"-"][0] componentsSeparatedByString:@":"];
    for (int i = 0; i < _hoursArray.count; i++) {
        if ([_hoursArray[i] isEqualToString:array[0]]) {
            row1 = i;
        }
    }
    for (int i = 0; i < _minsArray.count; i++) {
        if ([_minsArray[i] isEqualToString:array[1]]) {
            row2 = i;
        }
    }
    [_pickerView selectRow:row1 inComponent:0 animated:YES];
    [_pickerView selectRow:row2 inComponent:1 animated:YES];
}

#pragma mark 点击cell，pickerView 联动
- (void)clickfirstCell:(BOOL)isfirst timeStr:(NSString *)timeStr
{
    _isFirst = isfirst;
    NSInteger row1 = 0, row2 = 0;
    NSArray *array = [timeStr componentsSeparatedByString:@":"];
    for (int i = 0; i < _hoursArray.count; i++) {
        if ([_hoursArray[i] isEqualToString:array[0]]) {
            row1 = i;
        }
    }
    for (int i = 0; i < _minsArray.count; i++) {
        if ([_minsArray[i] isEqualToString:array[1]]) {
            row2 = i;
        }
    }
    [_pickerView selectRow:row1 inComponent:0 animated:YES];
    [_pickerView selectRow:row2 inComponent:1 animated:YES];
}

#pragma mark - switch statues change
- (void)siwitchChange
{
    if (_swit.on) {
        _swit.on = YES;
        [_tableView addSubview:self.pickerView];
    } else {
        _swit.on = NO;
        _timeFromlabel = nil;
        _timeTolabel = nil;
        [self deallocPickerView];
    }
    [_tableView reloadData];
}

#pragma mark - initPickerView
- (UIPickerView *)pickerView
{
    if (!_pickerView) {
        _pickerView = [[UIPickerView alloc] initWithFrame:CGRectMake(0, self.view.height-150-100, MTScreenW, 150)];
        _pickerView.delegate = self;
        _pickerView.dataSource = self;
        _pickerView.backgroundColor = MTConfigColor(@"MTSetNightModel_PickerBg_Color");
        _pickerView.layer.borderWidth = 0.5;
        UIColor *borderColor = MTConfigColor(@"MTSetNightModel_PickerBorder_Color");
        _pickerView.layer.borderColor = borderColor.CGColor;
    }
    return _pickerView;
}

- (void)deallocPickerView
{
    [_pickerView removeFromSuperview];
    _pickerView = nil;
}

#pragma mark - pickerView
- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView
{
    return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    if (0 == component) {
        return _hoursArray.count;
    } else {
        return _minsArray.count;
    }
}

-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (0 == component) {
        return _hoursArray[row];
    } else {
        return _minsArray[row];
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    
    NSString *hours, *min;
    if (component == 0) {
        NSInteger minIndex = [pickerView selectedRowInComponent:1];
        hours = [_hoursArray objectAtIndex:row];
        min = [_minsArray objectAtIndex:minIndex];
    }else if (component == 1){
        NSInteger hourIndex = [pickerView selectedRowInComponent:0];
        hours = [_hoursArray objectAtIndex:hourIndex];
        min = [_minsArray objectAtIndex:row];
    }
    if (_isFirst) {
        _timeFromlabel.text = [NSString stringWithFormat:@"%@:%@", hours, min];
//        [_timeFromlabel setNeedsDisplay];
    }else{
        _timeTolabel.text = [NSString stringWithFormat:@"%@:%@", hours, min];
//        [_timeTolabel setNeedsDisplay];
    }
}


@end
